package com.flashflexpro.tanksinbattle.scene {
import com.flashflexpro.tanksinbattle.scene.dto.DependencyDto;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.system.ApplicationDomain;

[Event(name="complete", type="flash.events.Event")]
[Event(name="ioError", type="flash.events.IOErrorEvent")]

/**
 * IOErrorEvent.IO_ERROR
 * Focus on load dependency modules
 * Before dispatch readyToStart,
 * a battle scene needs to load code swf, skin swf, all sub modules
 * a menu scene needs to load skin swf( because code skin already compiled into Loader, @see LoaderMain )
 */
public class ModuleDependencyResolver extends EventDispatcher {

    private var _modules:Array;
    private var _cursor:int = 0;


    public function get modules():Array{
        return _modules;
    }

    public function get cursor():int {
        return _cursor;
    }

    private var _rslEnable:Boolean;
    public function resolve(dtos:Array, rslEnabled=false):void {
        if (_cursor != 0) {
            throw new Error("ongoing, cursor:" + _cursor);
        }
        _rslEnable = rslEnabled;
        trace( "ModuleDependecyResolver resolveing:" + dtos );
        _modules = dtos;
        resolveCurrent();
    }

    private function resolveCurrent():void {

        var sceneDto:DependencyDto = _modules[ _cursor ];
        trace( "ModuleDependecyResolver resolveCurrent:" + sceneDto.entryClass );
        if (_rslEnable && ApplicationDomain.currentDomain.hasDefinition(sceneDto.entryClass)) {
            onCurrentResolve();
            return;
        }

        var s:SingleModuleResolver = new SingleModuleResolver();
        s.addEventListener(Event.COMPLETE, onCurrentResolve);
        s.addEventListener(IOErrorEvent.IO_ERROR, onIoError);
        s.resolve(sceneDto, _rslEnable) ;
    }

    private function onIoError(event:IOErrorEvent):void {
        dispatchEvent( event );
    }

    private function onCurrentResolve(event:Event = null):void {
        if( event != null ){
            ( event.target as EventDispatcher ).removeEventListener(Event.COMPLETE, onCurrentResolve);
        }
        var sceneDto:DependencyDto = _modules[ _cursor ];
        trace( "ModuleDependecyResolver onCurrentResolve:" + sceneDto.entryClass );
        if (_cursor < _modules.length - 1) {
            _cursor ++;
            resolveCurrent();
        }
        else {
            dispatchEvent(new Event(Event.COMPLETE));
            _cursor = 0;
        }
    }


}

}